package com.lee.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.lee.handle.CustomBlockHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/rateLimit")
public class RateLimitController {

    /**
     * 按资源名称限流，需要指定限流处理逻辑
     *
     * @return
     */
    @GetMapping("/byResource")
    @SentinelResource(value = "byResource", blockHandler = "handleException")
    public Map<String,Object> byResource() {
        Map<String,Object> result = new HashMap<>();
        result.put("name","按资源名称限流");
        result.put("code",200);
        return result ;
    }

    /**
     * 按url限流，有默认的限流处理逻辑
     *
     * @return
     */
    @GetMapping("byUrl")
    @SentinelResource(value = "byUrl", blockHandler = "handleException")
    public Map<String,Object> byUrl() {
        Map<String,Object> result = new HashMap<>();
        result.put("name","按url限流");
        result.put("code",200);
        return result ;
    }

    public Map<String,Object> handleException(BlockException exception) {
        Map<String,Object> result = new HashMap<>();
        result.put("name",exception.getClass().getCanonicalName());
        result.put("code",200);
        return result ;
    }

    @GetMapping("/customBlockHandler")
    @SentinelResource(value = "customBlockHandler", blockHandler = "handleException", blockHandlerClass = CustomBlockHandler.class)
    public Map<String,Object> blockHandler() {
        Map<String,Object> result = new HashMap<>();
        result.put("name","限流成功");
        result.put("code",200);
        return result ;
    }


}
